<template>
  <el-drawer
    v-model="drawer"
    title="评论"
    @close="closeHandler"
  >
    <div class="comment-section">
      <div class="comment-input">
        <el-input
          v-model="submitData.content"
          placeholder="欢迎评论"
          :rows="3"
          type="textarea"
          :maxlength="1000"
        />
        <div class="input-footer">
          <span>还能输入{{ 1000 - submitData.content.length }}个字符</span>
          <el-button
            type="primary"
            @click="submitComment"
            :disabled="!submitData.content.trim()"
          >评论</el-button>
        </div>
      </div>
      <div
        class="comment-list"
        v-infinite-scroll="handleScroll"
        :infinite-scroll-disabled="noMore"
      >
        <div
          v-for="comment in commentList"
          :key="comment.id"
          class="comment-item"
        >
          <div class="comment-header">
            <img class="comment-avatar" :size="30" src="@/assets/images/avatar.png" />
            <span class="comment-username">{{ comment.userId }}</span>
            <span class="comment-time">{{ dayjs(comment.createTime).format("YYYY-MM-DD HH:MM") }}</span>
          </div>
          <div class="comment-body">{{ comment.content }}</div>
        </div>
        <div class="bottom-line" v-if="noMore && current != 1">人家也是有底线的</div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref } from 'vue'
import { useRoute } from "vue-router";
import { getCommentAPI, submitCommentAPI } from "@/api/comment.js";
import { useUserStore } from "@/stores/userStore.js";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";

const drawer = ref(false);
const route = useRoute()
const current = ref(1) // 当前页数

// 评论数据
const commentList = ref([])
const isLoading = ref(false)
const noMore = ref(false) // 没有更多，禁止加载

// 获取评论
const getCommentList = async () => {
  if (isLoading.value) return; // 如果正在加载，则直接返回
  isLoading.value = true; // 开始加载

  // 调用接口获取评论
  const res = await getCommentAPI({
    id: submitData.value.blogId,
    current: current.value
  })

  // 判断是否还有数据
  if (res.data.length === 0) {
    noMore.value = true
  }

  // 数据拼接
  commentList.value = current.value === 1 ? res.data : [...commentList.value, ...res.data];
  isLoading.value = false; // 加载结束
}

// 无限滚动逻辑
const handleScroll = () => {
  if (isLoading.value) return;
  current.value++
  getCommentList()
};

const userStore = useUserStore() // 用户仓库
// 发布评论的参数
const submitData = ref({
  "blogId": route.query.id,
  "content": "",
  "userId": userStore.userInfo.userId
})
// 发布评论
const submitComment = async () => {
  try {
    const res = await submitCommentAPI(submitData.value) // 发布评论
    if (res.code === 200) {
      reset() // 重置参数
      getCommentList() // 重新渲染
      ElMessage.success('发布成功') // 提示用户
    }
  } catch (err) {
    ElMessage.error('发布评论失败')
  }
}

// 重置参数
const reset = () => {
  current.value = 1 // 重置页数
  submitData.value.content = '' // 重置评论内容
  noMore.value = false // 重置是否禁止无限滚动
}

// 开启抽屉
const openDrawer = () => {
  reset() // 重置参数
  commentList.value = []
  drawer.value = true
  getCommentList()
}

const emits = defineEmits(['closeDrawer'])
// 关闭抽屉
const closeHandler = () => {
  emits('closeDrawer')
  drawer.value = false
}

defineExpose({
  openDrawer
})
</script>

<style scoped>
.comment-section {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
}
.comment-input {
  margin-bottom: 16px;
}
.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}
.comment-item {
  margin-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 16px;
}
.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.comment-username {
  margin-left: 8px;
  font-weight: 500;
}
.comment-time {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}
.comment-body {
  line-height: 1.5;
}
.bottom-line {
  text-align: center;
  font-size: 12px;
  color: #999;
}
</style>
